//
//  ObjectSprite.cpp
//  StarBugs
//
//  Created by ?? ? on 12/28/11.
//  Copyright (c) 2011 antisword@playorca.com. All rights reserved.
//

#include "Object/ObjectSprite.h"

ObjectSprite::~ObjectSprite()
{
    if(frameArray)
    {
        frameArray->removeAllObjects();
        frameArray->release();
        frameArray = NULL;
    }
//    
//    if(mainSprite)
//    {
//        mainSprite->removeAllChildrenWithCleanup(true);
//        mainSprite->release();
//        mainSprite = NULL;
//    }
}

ObjectSprite::ObjectSprite()
{
    frameArray = CCArray::create();
    frameArray->retain();
    frameMax = 0;
    num = 0;
    mainBody = NULL;
    mainSprite = NULL;
    winSize = CCSize(320, 480);
}

void ObjectSprite::setFrame(int i, cocos2d::CCSpriteFrame *frame)
{
    frameMax += 1;
    if(i == 0)
        mainSprite->setDisplayFrame(frame);
    frameArray->insertObject(frame, i);
}

void ObjectSprite::tick(float td)
{
    if(isRepeatForever == false)
        if(num + 1 == frameMax)
        {
            mainSprite->setDisplayFrame((CCSpriteFrame*)frameArray->objectAtIndex(0));
            unschedule(schedule_selector(ObjectSprite::tick));
            return;
        }
            
    num = (num+1) % frameMax;
    mainSprite->setDisplayFrame((CCSpriteFrame*)frameArray->objectAtIndex(num));
}

void ObjectSprite::startAnimation(bool repeat)
{
    unschedule(schedule_selector(ObjectSprite::tick));
    isRepeatForever = repeat;
    if(frameMax > 1)
    {
        num = 0;
        schedule(schedule_selector(ObjectSprite::tick), 0.1);
    }
}

void ObjectSprite::pause()
{
    pauseSchedulerAndActions();
    mainSprite->pauseSchedulerAndActions();
};
void ObjectSprite::resume()
{
    resumeSchedulerAndActions();
    mainSprite->resumeSchedulerAndActions();
};

void ObjectSprite::setMove(cocos2d::CCPoint pt)
{
    if(mainBody != NULL)
    {
        mainBody->SetTransform(b2Vec2(pt.x/PTM_RATIO, pt.y/PTM_RATIO), CC_DEGREES_TO_RADIANS(bodyAngle));
        position = pt;
    }
    else if(mainSprite != NULL)
    {
        mainSprite->setPosition(pt);
        position = pt;
    }
}